package com.school.controller;

import com.alibaba.druid.util.StringUtils;
import com.school.model.Department;
import com.school.model.ResultModel;
import com.school.model.Role;
import com.school.service.DepartmentService;
import com.school.service.RoleService;
import com.school.tool.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller()
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @PostMapping("")
    public @ResponseBody ResultModel insertDepartment(@Param("name") String name){
        if(StringUtils.isEmpty(name)){
            return Result.error("学系名不能为空!");
        }
        Department role=new Department();
        role.setName(name);
        role.setIsDelete(1);
        int resultCode=departmentService.insertSelective(role);
        if(resultCode>0){
            return Result.success();
        }else if(resultCode==-1){
            return Result.error("添加失败，学系名重复！");
        }else{
            return Result.error("添加失败！");
        }
    }

    @PostMapping("/id")
    public @ResponseBody ResultModel updateDepartment(@Param("id") Integer id,@Param("name")String name){
        if(id==null){
            return Result.error("主键不能为空");
        }
        if(StringUtils.isEmpty(name)){
            return Result.success();
        }
        Department role=new Department();
        role.setId(id);
        role.setName(name);
        int resultCode=departmentService.updateByPrimaryKeySelective(role);
        if(resultCode>0){
            return Result.success();
        }else if(resultCode==-1){
            return Result.error("修改失败，学系名重复！");
        }else{
            return Result.error("添加失败！");
        }
    }


    @GetMapping
    public @ResponseBody ResultModel getAllDepartment(){
        List<Department> result=departmentService.getArray();
        return Result.success(result);
    }

    @GetMapping("/id")
    public @ResponseBody ResultModel getDepartment(@Param("id") Integer id){
        if(id==null){
            return Result.error("参数错误");
        }
        return Result.success(departmentService.selectByPrimaryKey(id));
    }

    @PostMapping("/{id}")
    public @ResponseBody ResultModel deleteDepartment(@PathVariable("id") Integer id){
        if(id==null){
            return Result.error("参数错误");
        }
        return Result.success(departmentService.deleteByPrimaryKey(id));
    }

}
